import db.database
import log


def getAppAuthByAppId(appId: str):
    conn = db.database.get_connection()
    with conn.cursor() as cursor:
        try:
            cursor.execute("SELECT app_secret, app_name, source "
                           "FROM sys_apps WHERE app_id='" + appId + "'")
            result = cursor.fetchone()

            return result
        except Exception as e:
            log.logger.error(e.__str__())
            conn.rollback()
        finally:
            cursor.close()
            conn.close()


def getAppAuthByAppIdUserId(appId: str, userId: str):
    conn = db.database.get_connection()
    with conn.cursor() as cursor:
        try:
            cursor.execute("SELECT user_pass "
                           "FROM sys_users WHERE app_id='" + appId + "' and user_id='" + userId + "'")
            result = cursor.fetchone()

            return result
        except Exception as e:
            log.logger.error(e.__str__())
            conn.rollback()
        finally:
            cursor.close()
            conn.close()


def registerApp(appId: str, userId: str, userPass: str):
    conn = db.database.get_connection()
    with conn.cursor() as cursor:
        try:
            sql = "INSERT INTO sys_users (app_id, user_id, user_pass) VALUES (%s, %s, %s)"
            values = (appId, userId, userPass)

            cursor.execute(sql, values)

            conn.commit()

            return True
        except Exception as e:
            log.logger.error(e.__str__())
            conn.rollback()

            return False
        finally:
            cursor.close()
            conn.close()


def unregisterApp(appId: str, userId: str):
    conn = db.database.get_connection()
    with conn.cursor() as cursor:
        try:
            sql = "DELETE FROM sys_users WHERE app_id='" + appId + "' and user_id = '" + userId + "'"

            cursor.execute(sql)

            conn.commit()

            return True
        except Exception as e:
            log.logger.error(e.__str__())
            conn.rollback()

            return False
        finally:
            cursor.close()
            conn.close()
